﻿using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyWrite.API.Appicant.Command.MenuCommand;
using MediatR;

namespace B.S.DataBase.MyWrite.API.Appicant.CommandHandler.MenuCommandHandler
{
    /// <summary>
    /// 批量删除菜单(逻辑删除)命令执行
    /// </summary>
    public class DeleteMenuCommandHandler : IRequestHandler<DeleteMenuCommand, APIResult<string>>
    {
        private readonly IBaseRepository<MenuModel> menuRepos;

        public DeleteMenuCommandHandler(IBaseRepository<MenuModel> menuRepos)
        {
            this.menuRepos = menuRepos;
        }
        /// <summary>
        /// 批量删除菜单(逻辑删除)
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<APIResult<string>> Handle(DeleteMenuCommand request, CancellationToken cancellationToken)
        {
            APIResult<string> result = new APIResult<string>();
            //1.查询当前对象 及 父级下的所有子子级
            var list = menuRepos.GetAll().Result.Where(x => x.IsDeleted == false).ToList();
            //2.递归查询
            var menulist = GetMenuList(list, request.MenuId);
            //3,.查询到删除
            var res = "";
            //4.当前修改
            var getmenu = menuRepos.GetAll().Result.FirstOrDefault(x => x.MenuId == request.MenuId);
            getmenu.IsDeleted = true;
            res = menuRepos.Update(getmenu).Result.ToString();
            foreach (var item in menulist)
            {
                item.IsDeleted = true;
                res =  menuRepos.Update(item).Result.ToString();
            }
            result.data = res;
            return await Task.FromResult(result);
        }

        /// <summary>
        /// 递归查询
        /// </summary>
        /// <param name="menus"></param>
        /// <param name="ParentId"></param>
        /// <returns></returns>
        public IEnumerable<MenuModel> GetMenuList(List<MenuModel> menus, int MenuId)
        {
            var children = menus.Where(x => x.ParentId == MenuId);
            foreach (var item in children)
            {
                yield return item;
                var subChildren = GetMenuList(menus, item.MenuId);
                foreach (var subItem in subChildren)
                {
                    yield return subItem;
                }
            }
        }


    }
}
